package com.example.tupiancs34;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.OpenableColumns;
import android.util.Log;
import android.webkit.MimeTypeMap;

import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ImageContentProvider extends ContentProvider {

    private static final String TAG = "ImageContentProvider";
    private static final String AUTHORITY = "com.example.tupiancs34.provider";
    private static final String BASE_PATH = "images";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);

    @Override
    public boolean onCreate() {
        Log.d(TAG, "ImageContentProvider onCreate() called - 开始初始化");
        
        try {
            // 预加载assets目录，确保ContentProvider完全初始化
            AssetManager assetManager = getContext().getAssets();
            String[] imageFiles = assetManager.list("images");
            Log.d(TAG, "ContentProvider初始化完成，发现 " + (imageFiles != null ? imageFiles.length : 0) + " 张图片");
            
            if (imageFiles != null) {
                for (String fileName : imageFiles) {
                    if (isImageFile(fileName)) {
                        Log.d(TAG, "预加载图片: " + fileName);
                    }
                }
            }
            
            Log.d(TAG, "ImageContentProvider 自动启动成功！");
            return true;
        } catch (IOException e) {
            Log.e(TAG, "ContentProvider初始化失败", e);
            return false;
        }
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.d(TAG, "query() called with URI: " + uri);
        
        // 定义返回的列：文件名、文件大小、base64数据
        String[] columns = projection != null ? projection : new String[]{
                OpenableColumns.DISPLAY_NAME,
                OpenableColumns.SIZE,
                "base64_data"
        };
        
        MatrixCursor cursor = new MatrixCursor(columns);

        try {
            AssetManager assetManager = getContext().getAssets();
            String[] imageFiles = assetManager.list("images");
            Log.d(TAG, "Found " + (imageFiles != null ? imageFiles.length : 0) + " files in assets/images");
            
            if (imageFiles != null) {
                for (String fileName : imageFiles) {
                    if (isImageFile(fileName)) {
                        MatrixCursor.RowBuilder row = cursor.newRow();
                        
                        // 添加文件名
                        row.add(fileName);
                        
                        try {
                            // 获取文件大小
                            AssetFileDescriptor afd = assetManager.openFd("images/" + fileName);
                            long fileSize = afd.getLength();
                            row.add(fileSize);
                            afd.close();
                            
                            // 将图片转换为base64
                            String base64Data = convertImageToBase64(assetManager, fileName);
                            row.add(base64Data);
                            
                            Log.d(TAG, "Added file to cursor: " + fileName + ", size: " + fileSize + ", base64 length: " + 
                                  (base64Data != null ? base64Data.length() : 0));
                        } catch (IOException e) {
                            row.add(0L);  // 文件大小
                            row.add("");  // 空的base64数据
                            Log.e(TAG, "Error processing file: " + fileName, e);
                        }
                    }
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "Error listing assets/images directory", e);
        }

        Log.d(TAG, "Returning cursor with " + cursor.getCount() + " rows");
        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        String fileName = uri.getLastPathSegment();
        if (fileName != null) {
            String extension = MimeTypeMap.getFileExtensionFromUrl(fileName);
            return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return "image/*";
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
        Log.d(TAG, "openFile() called with URI: " + uri + ", mode: " + mode);
        
        try {
            String fileName = uri.getLastPathSegment();
            if (fileName == null) {
                Log.e(TAG, "Invalid URI - no filename: " + uri);
                throw new FileNotFoundException("Invalid URI: " + uri);
            }

            Log.d(TAG, "Opening file: images/" + fileName);
            AssetManager assetManager = getContext().getAssets();
            AssetFileDescriptor afd = assetManager.openFd("images/" + fileName);
            Log.d(TAG, "Successfully opened file: " + fileName);
            return afd.getParcelFileDescriptor();
        } catch (IOException e) {
            Log.e(TAG, "Cannot open file: " + uri, e);
            throw new FileNotFoundException("Cannot open file: " + uri);
        }
    }

    private boolean isImageFile(String fileName) {
        String extension = fileName.toLowerCase();
        return (fileName.startsWith("image_") && (extension.endsWith(".jpg") || extension.endsWith(".jpeg") ||
               extension.endsWith(".png") || extension.endsWith(".gif") || 
               extension.endsWith(".bmp") || extension.endsWith(".webp")));
    }
    
    /**
     * 将图片文件转换为base64字符串
     */
    private String convertImageToBase64(AssetManager assetManager, String fileName) {
        try {
            InputStream inputStream = assetManager.open("images/" + fileName);
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            
            // 读取整个文件到字节数组
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            
            inputStream.close();
            byte[] fileBytes = outputStream.toByteArray();
            
            // 将整个文件转换为base64
            String base64Data = Base64.encodeToString(fileBytes, Base64.DEFAULT);
            Log.d(TAG, "Successfully converted " + fileName + " to base64, length: " + base64Data.length());
            return base64Data;
            
        } catch (IOException e) {
            Log.e(TAG, "Error converting " + fileName + " to base64", e);
            return "";
        }
    }
}
